<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang>
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blogs/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blogs/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blogs/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blogs/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blogs/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="React,">










<meta name="keywords" content="React">
<meta property="og:type" content="article">
<meta property="og:title" content="Redux实现原理(推导Redux基本用法)">
<meta property="og:url" content="https://wangzichong.gitee.io/blogs/2020/12/20/t-React/derivation-of-redux/index.html">
<meta property="og:site_name" content="Reading Notes">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://pic.downk.cc/item/5fe804883ffa7d37b3a6dc05.jpg">
<meta property="og:updated_time" content="2021-08-02T13:50:53.673Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Redux实现原理(推导Redux基本用法)">
<meta name="twitter:image" content="https://pic.downk.cc/item/5fe804883ffa7d37b3a6dc05.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blogs/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://wangzichong.gitee.io/blogs/2020/12/20/t-React/derivation-of-redux/">





  <title>Redux实现原理(推导Redux基本用法) | Reading Notes</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blogs/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Reading Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Codes Change Life</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blogs/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blogs/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blogs/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://wangzichong.gitee.io/blogs/blogs/2020/12/20/t-React/derivation-of-redux/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zichong">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blogs/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Reading Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Redux实现原理(推导Redux基本用法)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-12-20T17:12:21+08:00">
                2020-12-20
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogs/categories/学习笔记/" itemprop="url" rel="index">
                    <span itemprop="name">学习笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          
              <div class="post-description">
                   
              </div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <a id="more"></a>

<h3 id="Redux-三大原则"><a href="#Redux-三大原则" class="headerlink" title="Redux 三大原则"></a>Redux 三大原则</h3><ul>
<li>单一数据源<ul>
<li>应用程序的所有数据都挂载在同一对象下面，方便管理</li>
<li>同一信息量的数据，只有一份，避免不同步</li>
</ul>
</li>
<li>状态不可变<ul>
<li>修改数据的前后，数据源不再是同一个对象(可以实现时间旅行，也可以避免直接去修改数据的行为)</li>
</ul>
</li>
<li>纯函数修改状态<ul>
<li>没有副作用，不依赖外部变量，同样的输入产生同样的输出</li>
</ul>
</li>
</ul>
<h3 id="Hooks-实现一个简单的-TodoList-组件"><a href="#Hooks-实现一个简单的-TodoList-组件" class="headerlink" title="Hooks 实现一个简单的 TodoList 组件"></a>Hooks 实现一个简单的 TodoList 组件</h3><ul>
<li>TodoList 由 Control，TodoItem，Todos 三个组件组成</li>
<li><img src="https://pic.downk.cc/item/5fe804883ffa7d37b3a6dc05.jpg">

</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 函数式组件最好用memo包裹，让其自我实现 shouldcomponentdidupate 的功能</span></span><br><span class="line"><span class="keyword">const</span> Control = memo(<span class="function"><span class="keyword">function</span> <span class="title">Control</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; addTodo &#125; = props;</span><br><span class="line">  <span class="keyword">const</span> inputRef = useRef();</span><br><span class="line">  <span class="keyword">const</span> onSubmit = <span class="function">(<span class="params">e</span>) =&gt;</span> &#123;</span><br><span class="line">    e.preventDefault();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> newText = inputRef.current.value.trim();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (newText.length === <span class="number">0</span>) <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">    addTodo(&#123;</span><br><span class="line">      id: <span class="keyword">new</span> <span class="built_in">Date</span>().valueOf(),</span><br><span class="line">      text: newText,</span><br><span class="line">      complete: <span class="literal">false</span></span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    inputRef.current.value = <span class="string">''</span>;</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div className=<span class="string">"control"</span>&gt;</span><br><span class="line">      &lt;div&gt;todos&lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">      &lt;form onSubmit=&#123;onSubmit&#125;&gt;</span></span><br><span class="line"><span class="regexp">        &lt;input ref=&#123;inputRef&#125; type="text" className="new-todo" placeholder="what needs to be done?" /</span>&gt;</span><br><span class="line">      &lt;<span class="regexp">/form&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/</span>div&gt;</span><br><span class="line">  )</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> TodoItem = memo(<span class="function"><span class="keyword">function</span> <span class="title">TodoItem</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; <span class="attr">todo</span>: &#123; id, text, complete &#125;, toggleTodo, removeTodo &#125; = props;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> onChange = <span class="function"><span class="params">()</span> =&gt;</span> &#123; </span><br><span class="line">    toggleTodo(id);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> onRemove = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    removeTodo(id);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;li className=<span class="string">"todo-item"</span>&gt;</span><br><span class="line">      &lt;input type=<span class="string">"checkbox"</span> onChange=&#123;onChange&#125; checked=&#123;complete&#125; /&gt;</span><br><span class="line">      &lt;label className=&#123;complete ? <span class="string">'complete'</span> : <span class="string">''</span>&#125;&gt;&#123;text&#125;&lt;<span class="regexp">/label&gt;</span></span><br><span class="line"><span class="regexp">      &lt;button onClick=&#123;onRemove&#125;&gt;X&lt;/</span>button&gt;</span><br><span class="line">    &lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">  );</span></span><br><span class="line"><span class="regexp">&#125;);</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Todos = memo(<span class="function"><span class="keyword">function</span> <span class="title">Todos</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; todos, toggleTodo, removeTodo &#125; = props;</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;ul&gt;</span><br><span class="line">      &#123;</span><br><span class="line">        todos.map(<span class="function"><span class="params">todo</span> =&gt;</span> &#123;</span><br><span class="line">          <span class="comment">// 这里单独用了TodoItem而不是直接用li，是因为防止个别成员数据的变化，导致全部成员都得重新渲染</span></span><br><span class="line">          <span class="keyword">return</span> &lt;TodoItem key=&#123;todo.id&#125; todo=&#123;todo&#125; toggleTodo=&#123;toggleTodo&#125; removeTodo=&#123;removeTodo&#125; /&gt;</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">    &lt;/ul&gt;</span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> LS_KEY = <span class="string">'ls_key'</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">TodoList</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> [todos, setTodos] = useState([]);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 因为该函数需要向子组件传递，因此要包裹useCallback</span></span><br><span class="line">  <span class="keyword">const</span> addTodo = useCallback(<span class="function">(<span class="params">todo</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 参数为函数，可以避免对 todos 的依赖</span></span><br><span class="line">    setTodos(<span class="function"><span class="params">todos</span> =&gt;</span> [...todos, todo]);</span><br><span class="line">  &#125;, []);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> removeTodo = useCallback(<span class="function">(<span class="params">id</span>) =&gt;</span> &#123;</span><br><span class="line">    setTodos(<span class="function"><span class="params">todos</span> =&gt;</span> todos.filter(<span class="function"><span class="params">todo</span> =&gt;</span> todo.id !== id ));</span><br><span class="line">  &#125;, []);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> toggleTodo = useCallback(<span class="function">(<span class="params">id</span>) =&gt;</span> &#123;</span><br><span class="line">    setTodos(<span class="function"><span class="params">todos</span> =&gt;</span> todos.map(<span class="function"><span class="params">todo</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> todo.id === id ? &#123;</span><br><span class="line">        ...todo,</span><br><span class="line">        complete: !todo.complete</span><br><span class="line">      &#125; : todo;</span><br><span class="line">    &#125;));</span><br><span class="line">  &#125;, []);</span><br><span class="line"></span><br><span class="line">  useEffect(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> todos = <span class="built_in">JSON</span>.parse(localStorage.getItem(LS_KEY)) || [];</span><br><span class="line">    setTodos(todos);</span><br><span class="line">  &#125;, []);</span><br><span class="line"></span><br><span class="line">  useEffect(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    localStorage.setItem(LS_KEY, <span class="built_in">JSON</span>.stringify(todos));</span><br><span class="line">  &#125;, [todos]);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div className=<span class="string">"todo-list"</span>&gt;</span><br><span class="line">      &lt;Control addTodo=&#123;addTodo&#125; /&gt;</span><br><span class="line">      &lt;Todos todos=&#123;todos&#125; removeTodo=&#123;removeTodo&#125; toggleTodo=&#123;toggleTodo&#125; /&gt;</span><br><span class="line">    &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">  );</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="引入-action-和-dispatch-改造-TodoList-组件"><a href="#引入-action-和-dispatch-改造-TodoList-组件" class="headerlink" title="引入 action 和 dispatch 改造 TodoList 组件"></a>引入 action 和 dispatch 改造 TodoList 组件</h3><ul>
<li><p>用一种纯对象的方式(action)来表达对数据更新的操作，让每个action都经过一个中间函数(dispatch)，在该函数里集中处理副作用或者连带更新的行为</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> action = &#123;</span><br><span class="line">  type: <span class="string">'add'</span>, <span class="comment">// 用来描述对数据进行了怎样地操作</span></span><br><span class="line">  payload: todo  <span class="comment">// 用来描述执行这个操作需要哪些额外的数据</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>引入 dispatch 函数，让所有对数据的操作都经过它，由它来统一更新，在统一的位置拦截和debug所有操作</p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Control = memo(<span class="function"><span class="keyword">function</span> <span class="title">Control</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; dispatch &#125; = props;</span><br><span class="line">  <span class="keyword">const</span> inputRef = useRef();</span><br><span class="line">  <span class="keyword">const</span> onSubmit = <span class="function">(<span class="params">e</span>) =&gt;</span> &#123;</span><br><span class="line">    e.preventDefault();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> newText = inputRef.current.value.trim();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (newText.length === <span class="number">0</span>) <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// addTodo(&#123;</span></span><br><span class="line">    <span class="comment">//   id: new Date().valueOf(),</span></span><br><span class="line">    <span class="comment">//   text: newText,</span></span><br><span class="line">    <span class="comment">//   complete: false</span></span><br><span class="line">    <span class="comment">// &#125;);</span></span><br><span class="line"></span><br><span class="line">    dispatch(&#123; <span class="attr">type</span>: <span class="string">'add'</span>, <span class="attr">payload</span>: &#123;</span><br><span class="line">      id: <span class="keyword">new</span> <span class="built_in">Date</span>().valueOf(),</span><br><span class="line">      text: newText,</span><br><span class="line">      complete: <span class="literal">false</span></span><br><span class="line">    &#125;&#125;);</span><br><span class="line"></span><br><span class="line">    inputRef.current.value = <span class="string">''</span>;</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div className=<span class="string">"control"</span>&gt;</span><br><span class="line">      &lt;div&gt;todos&lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">      &lt;form onSubmit=&#123;onSubmit&#125;&gt;</span></span><br><span class="line"><span class="regexp">        &lt;input ref=&#123;inputRef&#125; type="text" className="new-todo" placeholder="what needs to be done?" /</span>&gt;</span><br><span class="line">      &lt;<span class="regexp">/form&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/</span>div&gt;</span><br><span class="line">  )</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> TodoItem = memo(<span class="function"><span class="keyword">function</span> <span class="title">TodoItem</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; <span class="attr">todo</span>: &#123; id, text, complete &#125;, dispatch &#125; = props;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> onChange = <span class="function"><span class="params">()</span> =&gt;</span> &#123; </span><br><span class="line">    <span class="comment">// toggleTodo(id);</span></span><br><span class="line">    dispatch(&#123; <span class="attr">type</span>: <span class="string">'toggle'</span>, <span class="attr">payload</span>: id &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> onRemove = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// removeTodo(id);</span></span><br><span class="line">    dispatch(&#123; <span class="attr">type</span>: <span class="string">'remove'</span>, <span class="attr">payload</span>: id &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;li className=<span class="string">"todo-item"</span>&gt;</span><br><span class="line">      &lt;input type=<span class="string">"checkbox"</span> onChange=&#123;onChange&#125; checked=&#123;complete&#125; /&gt;</span><br><span class="line">      &lt;label className=&#123;complete ? <span class="string">'complete'</span> : <span class="string">''</span>&#125;&gt;&#123;text&#125;&lt;<span class="regexp">/label&gt;</span></span><br><span class="line"><span class="regexp">      &lt;button onClick=&#123;onRemove&#125;&gt;X&lt;/</span>button&gt;</span><br><span class="line">    &lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">  );</span></span><br><span class="line"><span class="regexp">&#125;);</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Todos = memo(<span class="function"><span class="keyword">function</span> <span class="title">Todos</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; todos, dispatch &#125; = props;</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;ul&gt;</span><br><span class="line">      &#123;</span><br><span class="line">        todos.map(<span class="function"><span class="params">todo</span> =&gt;</span> &#123;</span><br><span class="line">          <span class="keyword">return</span> &lt;TodoItem key=&#123;todo.id&#125; todo=&#123;todo&#125; dispatch=&#123;dispatch&#125; /&gt;</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">    &lt;/ul&gt;</span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> LS_KEY = <span class="string">'ls_key'</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">TodoList</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> [todos, setTodos] = useState([]);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// dispatch 作为属性传入子组件中，因此要用useCallback包裹</span></span><br><span class="line">  <span class="keyword">const</span> dispatch = useCallback(<span class="function">(<span class="params">action</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; type, payload &#125; = action;</span><br><span class="line">    <span class="keyword">switch</span>(type) &#123;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'set'</span>:</span><br><span class="line">        setTodos(payload);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'add'</span>:</span><br><span class="line">        setTodos(<span class="function"><span class="params">todos</span> =&gt;</span> [...todos, payload]);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'remove'</span>:</span><br><span class="line">        setTodos(<span class="function"><span class="params">todos</span> =&gt;</span> todos.filter(<span class="function"><span class="params">todo</span> =&gt;</span> todo.id !== payload ));</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'toggle'</span>:</span><br><span class="line">        setTodos(<span class="function"><span class="params">todos</span> =&gt;</span> todos.map(<span class="function"><span class="params">todo</span> =&gt;</span> &#123;</span><br><span class="line">          <span class="keyword">return</span> todo.id === payload ? &#123;</span><br><span class="line">            ...todo,</span><br><span class="line">            complete: !todo.complete</span><br><span class="line">          &#125; : todo;</span><br><span class="line">        &#125;));</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">default</span>:</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;, []);</span><br><span class="line"></span><br><span class="line">  useEffect(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> todos = <span class="built_in">JSON</span>.parse(localStorage.getItem(LS_KEY)) || [];</span><br><span class="line">    dispatch(&#123; <span class="attr">type</span>: <span class="string">'set'</span>, <span class="attr">payload</span>: todos &#125;);</span><br><span class="line">    <span class="comment">// setTodos(todos);</span></span><br><span class="line">  &#125;, []);</span><br><span class="line"></span><br><span class="line">  useEffect(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    localStorage.setItem(LS_KEY, <span class="built_in">JSON</span>.stringify(todos));</span><br><span class="line">  &#125;, [todos]);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div className=<span class="string">"todo-list"</span>&gt;</span><br><span class="line">      &lt;Control dispatch=&#123;dispatch&#125; /&gt;</span><br><span class="line">      &lt;Todos todos=&#123;todos&#125; dispatch=&#123;dispatch&#125; /&gt;</span><br><span class="line">    &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">  );</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="引入-actionCreator，bindActionCreator-改造-TodoList"><a href="#引入-actionCreator，bindActionCreator-改造-TodoList" class="headerlink" title="引入 actionCreator，bindActionCreator 改造 TodoList"></a>引入 actionCreator，bindActionCreator 改造 TodoList</h3><ul>
<li><p>引入 actionCreator 将 action 的构造过程化</p>
</li>
<li><p>引入 bindActionCreator 将单个或者多个 actionCreator 转化为 dispatch(action) 的函数集合形式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// actionCreator</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createSet</span>(<span class="params">payload</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    type: <span class="string">'set'</span>,</span><br><span class="line">    payload</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createAdd</span>(<span class="params">payload</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    type: <span class="string">'add'</span>,</span><br><span class="line">    payload</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> &#123; createSet, createAdd &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 引入 bindActionCreator 将上面 export 的对象转换成以下的函数集合形式</span></span><br><span class="line">&#123;</span><br><span class="line">  createSet: <span class="function">(<span class="params">payload</span>) =&gt;</span> dispatch(createSet(payload)),</span><br><span class="line">  createAdd: <span class="function">(<span class="params">payload</span>) =&gt;</span> dispatch(createAdd(payload)),</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>总结:</p>
<ul>
<li>将 addTodo，removeTodo，toggleTodo 这三个操作todos的函数封装成一个(dispatch)</li>
<li>函数统一后，需要用参数来区分，将参数称为action，它由一个代表行为的 type 和 代表参数的 payload 构成</li>
<li>由于每次都需要创建 action 对象给 dispatch 用，因此将创建 action 的行为封装成函数即(actionCreator)</li>
<li>由于 actionCreator 创建的 action 还是要给 dispatch 用，所以创建一个 bindActionCreator 将 actionCreator 和 dispatch 函数打包到一起给组件调用</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createSet</span>(<span class="params">payload</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    type: <span class="string">'set'</span>,</span><br><span class="line">    payload</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createAdd</span>(<span class="params">payload</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    type: <span class="string">'add'</span>,</span><br><span class="line">    payload</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createRemove</span>(<span class="params">payload</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    type: <span class="string">'remove'</span>,</span><br><span class="line">    payload</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createToggle</span>(<span class="params">payload</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    type: <span class="string">'toggle'</span>,</span><br><span class="line">    payload</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">bindActionCreators</span>(<span class="params">actionCreators, dispatch</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> result = &#123;&#125;;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">in</span> actionCreators) &#123;</span><br><span class="line">    result[key] = <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">const</span> actionCreator = actionCreators[key];</span><br><span class="line">      <span class="keyword">const</span> action = actionCreator(...args);</span><br><span class="line">      dispatch(action);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Control = memo(<span class="function"><span class="keyword">function</span> <span class="title">Control</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; createAdd &#125; = props;</span><br><span class="line">  <span class="keyword">const</span> inputRef = useRef();</span><br><span class="line">  <span class="keyword">const</span> onSubmit = <span class="function">(<span class="params">e</span>) =&gt;</span> &#123;</span><br><span class="line">    e.preventDefault();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> newText = inputRef.current.value.trim();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (newText.length === <span class="number">0</span>) <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">    createAdd(&#123;</span><br><span class="line">      id: <span class="keyword">new</span> <span class="built_in">Date</span>().valueOf(),</span><br><span class="line">      text: newText,</span><br><span class="line">      complete: <span class="literal">false</span></span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    inputRef.current.value = <span class="string">''</span>;</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div className=<span class="string">"control"</span>&gt;</span><br><span class="line">      &lt;div&gt;todos&lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">      &lt;form onSubmit=&#123;onSubmit&#125;&gt;</span></span><br><span class="line"><span class="regexp">        &lt;input ref=&#123;inputRef&#125; type="text" className="new-todo" placeholder="what needs to be done?" /</span>&gt;</span><br><span class="line">      &lt;<span class="regexp">/form&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/</span>div&gt;</span><br><span class="line">  )</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> TodoItem = memo(<span class="function"><span class="keyword">function</span> <span class="title">TodoItem</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; <span class="attr">todo</span>: &#123; id, text, complete &#125;, createToggle, createRemove &#125; = props;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> onChange = <span class="function"><span class="params">()</span> =&gt;</span> &#123; </span><br><span class="line">    createToggle(id);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> onRemove = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    createRemove(id);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;li className=<span class="string">"todo-item"</span>&gt;</span><br><span class="line">      &lt;input type=<span class="string">"checkbox"</span> onChange=&#123;onChange&#125; checked=&#123;complete&#125; /&gt;</span><br><span class="line">      &lt;label className=&#123;complete ? <span class="string">'complete'</span> : <span class="string">''</span>&#125;&gt;&#123;text&#125;&lt;<span class="regexp">/label&gt;</span></span><br><span class="line"><span class="regexp">      &lt;button onClick=&#123;onRemove&#125;&gt;X&lt;/</span>button&gt;</span><br><span class="line">    &lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">  );</span></span><br><span class="line"><span class="regexp">&#125;);</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Todos = memo(<span class="function"><span class="keyword">function</span> <span class="title">Todos</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; todos, createToggle, createRemove &#125; = props;</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;ul&gt;</span><br><span class="line">      &#123;</span><br><span class="line">        todos.map(<span class="function"><span class="params">todo</span> =&gt;</span> &#123;</span><br><span class="line">          <span class="keyword">return</span> &lt;TodoItem key=&#123;todo.id&#125; todo=&#123;todo&#125; createToggle=&#123;createToggle&#125; createRemove=&#123;createRemove&#125; /&gt;</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">    &lt;/ul&gt;</span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> LS_KEY = <span class="string">'ls_key'</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">TodoList</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> [todos, setTodos] = useState([]);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// dispatch 作为属性传入子组件中，因此要用useCallback包裹</span></span><br><span class="line">  <span class="keyword">const</span> dispatch = useCallback(<span class="function">(<span class="params">action</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; type, payload &#125; = action;</span><br><span class="line">    <span class="keyword">switch</span>(type) &#123;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'set'</span>:</span><br><span class="line">        setTodos(payload);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'add'</span>:</span><br><span class="line">        setTodos(<span class="function"><span class="params">todos</span> =&gt;</span> [...todos, payload]);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'remove'</span>:</span><br><span class="line">        setTodos(<span class="function"><span class="params">todos</span> =&gt;</span> todos.filter(<span class="function"><span class="params">todo</span> =&gt;</span> todo.id !== payload ));</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'toggle'</span>:</span><br><span class="line">        setTodos(<span class="function"><span class="params">todos</span> =&gt;</span> todos.map(<span class="function"><span class="params">todo</span> =&gt;</span> &#123;</span><br><span class="line">          <span class="keyword">return</span> todo.id === payload ? &#123;</span><br><span class="line">            ...todo,</span><br><span class="line">            complete: !todo.complete</span><br><span class="line">          &#125; : todo;</span><br><span class="line">        &#125;));</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">default</span>:</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;, []);</span><br><span class="line"></span><br><span class="line">  useEffect(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> todos = <span class="built_in">JSON</span>.parse(localStorage.getItem(LS_KEY)) || [];</span><br><span class="line">    dispatch(createSet(todos))</span><br><span class="line">  &#125;, []);</span><br><span class="line"></span><br><span class="line">  useEffect(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    localStorage.setItem(LS_KEY, <span class="built_in">JSON</span>.stringify(todos));</span><br><span class="line">  &#125;, [todos]);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div className=<span class="string">"todo-list"</span>&gt;</span><br><span class="line">      &lt;Control &#123; ...bindActionCreators(&#123; createAdd &#125;, dispatch) &#125; /&gt;</span><br><span class="line">      &lt;Todos todos=&#123;todos&#125; &#123; ...bindActionCreators(&#123; createToggle, createRemove &#125;, dispatch) &#125; /&gt;</span><br><span class="line">    &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">  );</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<h3 id="引入-reducer-拆分数据"><a href="#引入-reducer-拆分数据" class="headerlink" title="引入 reducer 拆分数据"></a>引入 reducer 拆分数据</h3><ul>
<li><p>为什么叫reducer，从数据角度看(针对todos)，如果有多个action需要依次处理</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> todos = [</span><br><span class="line">  &#123;</span><br><span class="line">    complete: <span class="literal">false</span>,</span><br><span class="line">    id: <span class="number">1609050257118</span>,</span><br><span class="line">    text: <span class="string">'a'</span></span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    complete: <span class="literal">false</span>,</span><br><span class="line">    id: <span class="number">1609050257119</span>,</span><br><span class="line">    text: <span class="string">'b'</span></span><br><span class="line">  &#125;,&#123;</span><br><span class="line">    complete: <span class="literal">false</span>,</span><br><span class="line">    id: <span class="number">1609050257120</span>,</span><br><span class="line">    text: <span class="string">'c'</span></span><br><span class="line">  &#125;</span><br><span class="line">];</span><br><span class="line"><span class="keyword">const</span> actions = [</span><br><span class="line">  &#123;</span><br><span class="line">    type: <span class="string">'add'</span>,</span><br><span class="line">    payload: &#123;</span><br><span class="line">      complete: <span class="literal">false</span>,</span><br><span class="line">      id: <span class="number">1609050257121</span>,</span><br><span class="line">      text: <span class="string">'d'</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    type: <span class="string">'remove'</span>,</span><br><span class="line">    payload: <span class="number">1609050257118</span></span><br><span class="line">  &#125;</span><br><span class="line">];</span><br><span class="line"><span class="comment">// reduce里面的第一个回调函数：对于每一个action都会调用该函数，第一个参数是上一个action处理之后的todos，第二个参数为当前的action</span></span><br><span class="line">actions.reduce(<span class="function"><span class="keyword">function</span>(<span class="params">lastTodos, action</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">switch</span>(action.type) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">'add'</span>:</span><br><span class="line">      <span class="keyword">return</span> [...lastTodos, action.payload];</span><br><span class="line">    <span class="keyword">case</span> <span class="string">'remove'</span>:</span><br><span class="line">      <span class="keyword">return</span> lastTodos.filter(<span class="function"><span class="params">todo</span> =&gt;</span> todo.id !== action.payload);</span><br><span class="line">    <span class="keyword">default</span>:</span><br><span class="line">      <span class="keyword">return</span> lastTodos;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;, todos);</span><br><span class="line"><span class="comment">// 总结：因此形象地命名为reducer</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>按照数据来拆分(例如 todos，incrementCount 分别对应两个 reducer 函数)，dispatch只接收一个总的reducer(dispatch中调用reducer，并传入action)，因此需要将 reducer 对象转换成唯一的 reducer 函数</p>
</li>
<li><p>reducer 可以根据数据字段的维度去处理action，不同字段之间的数据就不会有过多的干扰</p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Control = memo(<span class="function"><span class="keyword">function</span> <span class="title">Control</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line"><span class="keyword">const</span> &#123; createAdd &#125; = props;</span><br><span class="line"><span class="keyword">const</span> inputRef = useRef();</span><br><span class="line"><span class="keyword">const</span> onSubmit = <span class="function">(<span class="params">e</span>) =&gt;</span> &#123;</span><br><span class="line">  e.preventDefault();</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> newText = inputRef.current.value.trim();</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (newText.length === <span class="number">0</span>) <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">  createAdd(&#123;</span><br><span class="line">    id: <span class="keyword">new</span> <span class="built_in">Date</span>().valueOf(),</span><br><span class="line">    text: newText,</span><br><span class="line">    complete: <span class="literal">false</span></span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  inputRef.current.value = <span class="string">''</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">return</span> (</span><br><span class="line">  &lt;div className=<span class="string">"control"</span>&gt;</span><br><span class="line">    &lt;div&gt;todos&lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">    &lt;form onSubmit=&#123;onSubmit&#125;&gt;</span></span><br><span class="line"><span class="regexp">      &lt;input ref=&#123;inputRef&#125; type="text" className="new-todo" placeholder="what needs to be done?" /</span>&gt;</span><br><span class="line">    &lt;<span class="regexp">/form&gt;</span></span><br><span class="line"><span class="regexp">  &lt;/</span>div&gt;</span><br><span class="line">  )</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> TodoItem = memo(<span class="function"><span class="keyword">function</span> <span class="title">TodoItem</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; <span class="attr">todo</span>: &#123; id, text, complete &#125;, createToggle, createRemove &#125; = props;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> onChange = <span class="function"><span class="params">()</span> =&gt;</span> &#123; </span><br><span class="line">    createToggle(id);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> onRemove = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    createRemove(id);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;li className=<span class="string">"todo-item"</span>&gt;</span><br><span class="line">      &lt;input type=<span class="string">"checkbox"</span> onChange=&#123;onChange&#125; checked=&#123;complete&#125; /&gt;</span><br><span class="line">      &lt;label className=&#123;complete ? <span class="string">'complete'</span> : <span class="string">''</span>&#125;&gt;&#123;text&#125;&lt;<span class="regexp">/label&gt;</span></span><br><span class="line"><span class="regexp">      &lt;button onClick=&#123;onRemove&#125;&gt;X&lt;/</span>button&gt;</span><br><span class="line">    &lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">  );</span></span><br><span class="line"><span class="regexp">&#125;);</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Todos = memo(<span class="function"><span class="keyword">function</span> <span class="title">Todos</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; todos, createToggle, createRemove &#125; = props;</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;ul&gt;</span><br><span class="line">      &#123;</span><br><span class="line">        todos.map(<span class="function"><span class="params">todo</span> =&gt;</span> &#123;</span><br><span class="line">          <span class="keyword">return</span> &lt;TodoItem key=&#123;todo.id&#125; todo=&#123;todo&#125; createToggle=&#123;createToggle&#125; createRemove=&#123;createRemove&#125; /&gt;</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">    &lt;/ul&gt;</span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> LS_KEY = <span class="string">'ls_key'</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">bindActionCreators</span>(<span class="params">actionCreators, dispatch</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> result = &#123;&#125;;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">in</span> actionCreators) &#123;</span><br><span class="line">    result[key] = <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">const</span> actionCreator = actionCreators[key];</span><br><span class="line">      <span class="keyword">const</span> action = actionCreator(...args);</span><br><span class="line">      dispatch(action);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">TodoList</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> [todos, setTodos] = useState([]);</span><br><span class="line">  <span class="keyword">const</span> [incrementCount, setIncrementCount] = useState(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> dispatch = useCallback(<span class="function">(<span class="params">action</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> state = &#123;</span><br><span class="line">      todos,</span><br><span class="line">      incrementCount</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> setters = &#123;</span><br><span class="line">      todos: setTodos,</span><br><span class="line">      incrementCount: setIncrementCount</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> newState = reducer(state, action);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">in</span> newState) &#123;</span><br><span class="line">      <span class="comment">// 根据 newState 返回的值(key, value)，来更新具体的 数据</span></span><br><span class="line">      setters[key](newState[key]);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;, [todos, incrementCount]);</span><br><span class="line"></span><br><span class="line">  useEffect(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> todos = <span class="built_in">JSON</span>.parse(localStorage.getItem(LS_KEY)) || [];</span><br><span class="line">    dispatch(createSet(todos))</span><br><span class="line">  &#125;, []);</span><br><span class="line"></span><br><span class="line">  useEffect(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    localStorage.setItem(LS_KEY, <span class="built_in">JSON</span>.stringify(todos));</span><br><span class="line">  &#125;, [todos]);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div className=<span class="string">"todo-list"</span>&gt;</span><br><span class="line">      &lt;Control &#123; ...bindActionCreators(&#123; createAdd &#125;, dispatch) &#125; /&gt;</span><br><span class="line">      &lt;Todos todos=&#123;todos&#125; &#123; ...bindActionCreators(&#123; createToggle, createRemove &#125;, dispatch) &#125; /&gt;</span><br><span class="line">    &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">  );</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reducers</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">combineReducers</span>(<span class="params">reducers</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// function reducer是一个全局的 reducer，在 dispatch 中调用</span></span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">reducer</span>(<span class="params">state, action</span>) </span>&#123; <span class="comment">// 该state包含所有数据</span></span><br><span class="line">    <span class="keyword">const</span> changed = &#123;&#125;;</span><br><span class="line">    <span class="comment">// 每次触发 action 所有的 reducers 都会走一遍，根据 action type 的不同返回具体的 new State</span></span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">let</span> key <span class="keyword">in</span> reducers) &#123;</span><br><span class="line">      changed[key] = reducers[key](state[key], action);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 返回所有状态的最新值</span></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      ...state,</span><br><span class="line">      ...changed</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> reducers = &#123;</span><br><span class="line">  <span class="comment">// 按照数据来拆分(todos，incrementCount 分别对应两个 reducer 函数) </span></span><br><span class="line">  todos(state, action) &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; type, payload &#125; = action;</span><br><span class="line">    <span class="keyword">switch</span>(type) &#123;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'set'</span>: </span><br><span class="line">        <span class="keyword">return</span> payload;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'add'</span>: </span><br><span class="line">        <span class="keyword">return</span> [...state, payload];</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'remove'</span>:</span><br><span class="line">        <span class="keyword">return</span> state.filter(<span class="function"><span class="params">todo</span> =&gt;</span> todo.id !== payload);</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'toggle'</span>: </span><br><span class="line">        <span class="keyword">return</span> state.map(<span class="function"><span class="params">todo</span> =&gt;</span> &#123;</span><br><span class="line">          <span class="keyword">return</span> todo.id === payload ? &#123;</span><br><span class="line">            ...todo,</span><br><span class="line">            complete: !todo.complete</span><br><span class="line">          &#125; : todo;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> state;</span><br><span class="line">  &#125;,</span><br><span class="line">  incrementCount(state, action) &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; type &#125; = action;</span><br><span class="line">    <span class="keyword">switch</span>(type) &#123;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'set'</span>:</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'add'</span>:</span><br><span class="line">          <span class="keyword">return</span> state + <span class="number">1</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> state;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> combineReducers(reducers);</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// actions</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createSet</span>(<span class="params">payload</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    type: <span class="string">'set'</span>,</span><br><span class="line">    payload</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createAdd</span>(<span class="params">payload</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    type: <span class="string">'add'</span>,</span><br><span class="line">    payload</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createRemove</span>(<span class="params">payload</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    type: <span class="string">'remove'</span>,</span><br><span class="line">    payload</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createToggle</span>(<span class="params">payload</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    type: <span class="string">'toggle'</span>,</span><br><span class="line">    payload</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="异步-Action"><a href="#异步-Action" class="headerlink" title="异步 Action"></a>异步 Action</h3><ul>
<li><p>actionCreator 返回一个 function，而不是一个纯对象</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createAdd</span>(<span class="params">payload</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 这里的state要保持最新，如果进行异步请求时，对数据做了更新，这时候如果不传入新的state，后续逻辑会基于老数据</span></span><br><span class="line">  <span class="comment">// 因此返回的函数的第二个值是函数等到异步结束后 getState</span></span><br><span class="line">  <span class="keyword">return</span> <span class="function">(<span class="params">dispatch, getState</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// state 用来查询现有的待办数据</span></span><br><span class="line">    <span class="comment">// dispatch 用来等查询之后发起纯对象的 action</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// setTimeout 模拟异步获取 id </span></span><br><span class="line">    setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">const</span> &#123; todos &#125; = getState();</span><br><span class="line"></span><br><span class="line">      <span class="keyword">if</span> (!todos.find(<span class="function"><span class="params">todo</span> =&gt;</span> todo.text === payload)) &#123;</span><br><span class="line">        dispatch(&#123;</span><br><span class="line">          type: <span class="string">'add'</span>,</span><br><span class="line">          payload: &#123;</span><br><span class="line">            id: <span class="keyword">new</span> <span class="built_in">Date</span>().valueOf(),</span><br><span class="line">            text: payload,</span><br><span class="line">            complete: <span class="literal">false</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">      alert(<span class="string">`<span class="subst">$&#123;payload&#125;</span> is duplicated`</span>)</span><br><span class="line">    &#125;, <span class="number">3000</span>);</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>增强 dispatch，允许 actionCreator 返回一个函数，函数需要有个 dispatch 来发起下一次 action，由于是异步的 action，需要有个函数来获取最新的 state</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> dispatch = <span class="function">(<span class="params">action</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> action === <span class="string">'function'</span>) &#123;</span><br><span class="line">    action(dispatch, () =&gt; store);</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
</li>
<li><p>更新后的全部代码</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Control = memo(<span class="function"><span class="keyword">function</span> <span class="title">Control</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; createAdd &#125; = props;</span><br><span class="line">  <span class="keyword">const</span> inputRef = useRef();</span><br><span class="line">  <span class="keyword">const</span> onSubmit = <span class="function">(<span class="params">e</span>) =&gt;</span> &#123;</span><br><span class="line">    e.preventDefault();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> newText = inputRef.current.value.trim();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (newText.length === <span class="number">0</span>) <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">    createAdd(newText);</span><br><span class="line"></span><br><span class="line">    inputRef.current.value = <span class="string">''</span>;</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div className=<span class="string">"control"</span>&gt;</span><br><span class="line">      &lt;div&gt;todos&lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">      &lt;form onSubmit=&#123;onSubmit&#125;&gt;</span></span><br><span class="line"><span class="regexp">        &lt;input ref=&#123;inputRef&#125; type="text" className="new-todo" placeholder="what needs to be done?" /</span>&gt;</span><br><span class="line">      &lt;<span class="regexp">/form&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/</span>div&gt;</span><br><span class="line">  )</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> TodoItem = memo(<span class="function"><span class="keyword">function</span> <span class="title">TodoItem</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; <span class="attr">todo</span>: &#123; id, text, complete &#125;, createToggle, createRemove &#125; = props;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> onChange = <span class="function"><span class="params">()</span> =&gt;</span> &#123; </span><br><span class="line">    createToggle(id);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> onRemove = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    createRemove(id);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;li className=<span class="string">"todo-item"</span>&gt;</span><br><span class="line">      &lt;input type=<span class="string">"checkbox"</span> onChange=&#123;onChange&#125; checked=&#123;complete&#125; /&gt;</span><br><span class="line">      &lt;label className=&#123;complete ? <span class="string">'complete'</span> : <span class="string">''</span>&#125;&gt;&#123;text&#125;&lt;<span class="regexp">/label&gt;</span></span><br><span class="line"><span class="regexp">      &lt;button onClick=&#123;onRemove&#125;&gt;X&lt;/</span>button&gt;</span><br><span class="line">    &lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">  );</span></span><br><span class="line"><span class="regexp">&#125;);</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Todos = memo(<span class="function"><span class="keyword">function</span> <span class="title">Todos</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; todos, createToggle, createRemove &#125; = props;</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;ul&gt;</span><br><span class="line">      &#123;</span><br><span class="line">        todos.map(<span class="function"><span class="params">todo</span> =&gt;</span> &#123;</span><br><span class="line">          <span class="keyword">return</span> &lt;TodoItem key=&#123;todo.id&#125; todo=&#123;todo&#125; createToggle=&#123;createToggle&#125; createRemove=&#123;createRemove&#125; /&gt;</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">    &lt;/ul&gt;</span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">bindActionCreators</span>(<span class="params">actionCreators, dispatch</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> result = &#123;&#125;;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">in</span> actionCreators) &#123;</span><br><span class="line">    result[key] = <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">const</span> actionCreator = actionCreators[key];</span><br><span class="line">      <span class="keyword">const</span> action = actionCreator(...args);</span><br><span class="line">      dispatch(action);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> LS_KEY = <span class="string">'ls_key'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 定义一个全局的 store</span></span><br><span class="line"><span class="keyword">const</span> store = &#123;</span><br><span class="line">  todos: [],</span><br><span class="line">  incrementCount: <span class="number">0</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">TodoList</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> [todos, setTodos] = useState([]);</span><br><span class="line">  <span class="keyword">const</span> [incrementCount, setIncrementCount] = useState(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">  useEffect(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 依赖变化的时候更新 store</span></span><br><span class="line">    <span class="built_in">Object</span>.assign(store, &#123;</span><br><span class="line">      todos,</span><br><span class="line">      incrementCount</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;, [todos, incrementCount]);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> dispatch = <span class="function">(<span class="params">action</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> setters = &#123;</span><br><span class="line">      todos: setTodos,</span><br><span class="line">      incrementCount: setIncrementCount</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> action === <span class="string">'function'</span>) &#123;</span><br><span class="line">      action(dispatch, () =&gt; store);</span><br><span class="line">      <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> newState = reducer(store, action);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">in</span> newState) &#123;</span><br><span class="line">      setters[key](newState[key]);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  useEffect(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> todos = <span class="built_in">JSON</span>.parse(localStorage.getItem(LS_KEY)) || [];</span><br><span class="line">    dispatch(createSet(todos))</span><br><span class="line">  &#125;, []);</span><br><span class="line"></span><br><span class="line">  useEffect(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    localStorage.setItem(LS_KEY, <span class="built_in">JSON</span>.stringify(todos));</span><br><span class="line">  &#125;, [todos]);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div className=<span class="string">"todo-list"</span>&gt;</span><br><span class="line">      &lt;Control &#123; ...bindActionCreators(&#123; createAdd &#125;, dispatch) &#125; /&gt;</span><br><span class="line">      &lt;Todos todos=&#123;todos&#125; &#123; ...bindActionCreators(&#123; createToggle, createRemove &#125;, dispatch) &#125; /&gt;</span><br><span class="line">    &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">  );</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">combineReducers</span>(<span class="params">reducers</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">reducer</span>(<span class="params">state, action</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> changed = &#123;&#125;;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">let</span> key <span class="keyword">in</span> reducers) &#123;</span><br><span class="line">      changed[key] = reducers[key](state[key], action);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      ...state,</span><br><span class="line">      ...changed</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> reducers = &#123;</span><br><span class="line">  todos(state, action) &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; type, payload &#125; = action;</span><br><span class="line">    <span class="keyword">switch</span>(type) &#123;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'set'</span>: </span><br><span class="line">        <span class="keyword">return</span> payload;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'add'</span>: </span><br><span class="line">        <span class="keyword">return</span> [...state, payload];</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'remove'</span>:</span><br><span class="line">        <span class="keyword">return</span> state.filter(<span class="function"><span class="params">todo</span> =&gt;</span> todo.id !== payload);</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'toggle'</span>: </span><br><span class="line">        <span class="keyword">return</span> state.map(<span class="function"><span class="params">todo</span> =&gt;</span> &#123;</span><br><span class="line">          <span class="keyword">return</span> todo.id === payload ? &#123;</span><br><span class="line">            ...todo,</span><br><span class="line">            complete: !todo.complete</span><br><span class="line">          &#125; : todo;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> state;</span><br><span class="line">  &#125;,</span><br><span class="line">  incrementCount(state, action) &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; type &#125; = action;</span><br><span class="line">    <span class="keyword">switch</span>(type) &#123;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'set'</span>:</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'add'</span>:</span><br><span class="line">          <span class="keyword">return</span> state + <span class="number">1</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> state;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> combineReducers(reducers);</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createSet</span>(<span class="params">payload</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    type: <span class="string">'set'</span>,</span><br><span class="line">    payload</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createAdd</span>(<span class="params">payload</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function">(<span class="params">dispatch, getState</span>) =&gt;</span> &#123;</span><br><span class="line">    setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">const</span> &#123; todos &#125; = getState();</span><br><span class="line">      <span class="keyword">if</span> (!todos.find(<span class="function"><span class="params">todo</span> =&gt;</span> todo.text === payload)) &#123;</span><br><span class="line">        dispatch(&#123;</span><br><span class="line">          type: <span class="string">'add'</span>,</span><br><span class="line">          payload: &#123;</span><br><span class="line">            id: <span class="keyword">new</span> <span class="built_in">Date</span>().valueOf(),</span><br><span class="line">            text: payload,</span><br><span class="line">            complete: <span class="literal">false</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">      alert(<span class="string">`<span class="subst">$&#123;payload&#125;</span> is duplicated`</span>)</span><br><span class="line">    &#125;, <span class="number">3000</span>);</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createRemove</span>(<span class="params">payload</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    type: <span class="string">'remove'</span>,</span><br><span class="line">    payload</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createToggle</span>(<span class="params">payload</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    type: <span class="string">'toggle'</span>,</span><br><span class="line">    payload</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blogs/tags/React/" rel="tag"># React</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blogs/2020/12/19/t-React/react-hooks-summary/" rel="next" title="React Hooks 复习总结">
                <i class="fa fa-chevron-left"></i> React Hooks 复习总结
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blogs/2021/08/02/t-React/react-micro-front-end/" rel="prev" title="微前端的探索与实现(React)">
                微前端的探索与实现(React) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">zichong</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blogs/archives/">
              
                  <span class="site-state-item-count">39</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blogs/categories/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blogs/tags/index.html">
                  <span class="site-state-item-count">14</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Redux-三大原则"><span class="nav-number">1.</span> <span class="nav-text">Redux 三大原则</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Hooks-实现一个简单的-TodoList-组件"><span class="nav-number">2.</span> <span class="nav-text">Hooks 实现一个简单的 TodoList 组件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#引入-action-和-dispatch-改造-TodoList-组件"><span class="nav-number">3.</span> <span class="nav-text">引入 action 和 dispatch 改造 TodoList 组件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#引入-actionCreator，bindActionCreator-改造-TodoList"><span class="nav-number">4.</span> <span class="nav-text">引入 actionCreator，bindActionCreator 改造 TodoList</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#引入-reducer-拆分数据"><span class="nav-number">5.</span> <span class="nav-text">引入 reducer 拆分数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#异步-Action"><span class="nav-number">6.</span> <span class="nav-text">异步 Action</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zichong</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blogs/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blogs/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/blogs/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blogs/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blogs/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blogs/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
